package edu.nf.takeoutdemo.commons.config;

import edu.nf.takeoutdemo.commons.json.JacksonObjectMapper;
import edu.nf.takeoutdemo.web.interceptor.TokenAdminInterceptor;
import edu.nf.takeoutdemo.web.interceptor.TokenUserInterceptor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 *
 * @author zjl
 * @date 2025/10/24
 */
@Configuration
@Slf4j
@RequiredArgsConstructor
public class MvcConfig extends WebMvcConfigurationSupport {
    private final TokenAdminInterceptor tokenAdminInterceptor;
    private final TokenUserInterceptor tokenUserInterceptor;
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
      log.info("开始注册自定义拦截器...");
      registry.addInterceptor(tokenAdminInterceptor).addPathPatterns("/admin/**")
              .excludePathPatterns("/admin/employee/login");
      registry.addInterceptor(tokenUserInterceptor).addPathPatterns("/user/**")
              .excludePathPatterns("/user/user/login")
              .excludePathPatterns("/user/shop/status");
    }
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true);
    }

    /**
     * 扩展spring mvc框架的消息转换器
     * @param converters
     */
    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("扩展消息转换器...");
        //创建一个消息转换器对象
        MappingJackson2HttpMessageConverter converter  = new MappingJackson2HttpMessageConverter();
        //需要为消息转换器设置一个对象转换器，对象转换器可以将Java对象序列化为json数据
        converter.setObjectMapper(new JacksonObjectMapper());
        //将自己的消息转换器加入到容器中
        converters.add(0,converter);
    }
}
